package com.virtualtrainer_01.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.virtualtrainer_01.model.Client;
import com.virtualtrainer_01.model.Exercise;
import com.virtualtrainer_01.model.Model;

public class NameList<T extends Model> {
	private List<Model> list;

	public NameList() {
		list = new ArrayList<Model>();

	}

	public void add(Model elem) {
		list.add(elem);
	}

	public Model get(int i) {
		return list.get(i);
	}

	public Model getElement(String name) {
		for (int i = 0; i < list.size(); i++) {
			if (name.equals(list.get(i).getName()))
				return this.get(i);
		}
		return null;
	}

	public int size() {
		return list.size();
	}

	public void clear() {
		list.clear();
	}

	private void sortValue(Hashtable<Exercise, Double> hTable, int limit) {

		@SuppressWarnings({ "unchecked", "rawtypes" })
		ArrayList<Map.Entry<Exercise, Double>> l = new ArrayList(
				hTable.entrySet());
		Collections.sort(l, new Comparator<Map.Entry<Exercise, Double>>() {

			public int compare(Map.Entry<Exercise, Double> o1,
					Map.Entry<Exercise, Double> o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		int count = 0;
		for (Entry<?, Double> entry : l) {
			if (count < limit) {
				Exercise ex = (Exercise) entry.getKey();
				list.add(ex);
				count++;
			}
		}
	}

	public void sortExercise(Client c, int limit) {
		if (this.list.get(0) instanceof Exercise == false)
			return;
		Hashtable<Exercise, Double> hTable = new Hashtable<Exercise, Double>();
		for (int i = 0; i < list.size(); i++)
			hTable.put((Exercise) list.get(i),
					getCalculatedDifficulty((Exercise) list.get(i), c));
		list.clear();
		sortValue(hTable, limit);
	}

	private double getCalculatedDifficulty(Exercise ex, Client c) {
		double cd = ex.getDifficultyRank();
		double clientForm = c.getHeigth() - c.getWeight();
		if (clientForm > 100)
			clientForm = -1;
		else if (clientForm == 100)
			clientForm = 0;
		else
			clientForm = 1;
		double clientExperience = 0;
		cd += clientExperience + clientForm;
		return cd;
	}

	public boolean Contains(Model e) {
		for (int m = 0; m < list.size(); m++)
			if (list.get(m).getName().equals(e.getName()))
				return true;
		return false;
	}
}
